package cn.murky.tenant.auth.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.murky.core.web.ApiResult;
import cn.murky.tenant.auth.domain.dto.LoginDto;
import cn.murky.tenant.auth.record.AuthRecord;
import cn.murky.tenant.core.utils.SecurityUtils;
import cn.murky.tenant.system.api.domain.vo.TenantMenuTreeVO;
import cn.murky.tenant.system.api.enums.MenuType;
import cn.murky.tenant.auth.service.IMurkyLoginService;
import cn.murky.tenant.auth.service.ITenantMenuService;
import cn.murky.tenant.core.SecurityTenantUserInfo;
import org.noear.solon.annotation.*;
import org.noear.solon.validation.annotation.Valid;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * 安全控制器
 *
 * @auth hans
 */
@Controller
@Valid
@Mapping("auth")
public class MurkyAuthController {

    @Inject
    private IMurkyLoginService iMurkyLoginService;
    @Inject
    private ITenantMenuService iTenantMenuService;

    /**
     * 登录
     * @param loginDto 登录参数
     */
    @Post
    @Mapping("login")
    public ApiResult<Map<String,Object>> login(@Body LoginDto loginDto) throws Exception {
        AuthRecord login = iMurkyLoginService.login(loginDto);
        Map<String,Object> result=new HashMap<>();
        result.put("token",login.saTokenInfo().getTokenValue());
        result.put("tenantId",login.tenantId());
        return ApiResult.ok(result);
    }

    /**
     * 登出
     */
    @Post
    @Mapping("logout")
    public ApiResult<?> logout() {
//        SecurityUtils.delUserMenu();
        SecurityUtils.delUserInfo();
        StpUtil.logout();
        return ApiResult.ok();
    }

    /**
     * 获取菜单
     * @return List<TenantMenuTreeVO>
     */
    @Get
    @Mapping("menu")
    public ApiResult<List<TenantMenuTreeVO>> menu() {
        return ApiResult.ok(iTenantMenuService.treeSysMenu(Arrays.asList(MenuType.MENU, MenuType.DIRECTORY)));
    }

    /**
     * 获取用户信息
     * @return SecurityTenantUserInfo
     */
    @Get
    @Mapping("info")
    public ApiResult<SecurityTenantUserInfo> userInfo() {
        return ApiResult.ok(iMurkyLoginService.userInfo());
    }
}
